//
//  FloorCardController.m
//  QRMaster
//
//  Created by myApple on 16/5/10.
//  Copyright © 2016年 myApple. All rights reserved.
//

#import "FloorCardController.h"
#import "FloorCardModel.h"
#import "FloorCardCell.h"
#import "ChineseString.h"
#import "pinyin.h"
#import "RequestNetWork.h"

@interface FloorCardController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>
{
    UITableView * floorTabelView;
    NSMutableArray * originDataArray;
    NSMutableArray * allSourceArray;
    NSMutableArray * floorDataArray;//排序后的数组
    NSMutableArray * selectIndexArray;//右边的索引
    UIImageView * submitImageView;
    UILabel * submitLabel;
    UIButton *  backBtn;
    
}

@end

@implementation FloorCardController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"floorCard", nil);
    self.view.backgroundColor = UIColorFromRGB(0xebebeb);
    [self prepareNavBtn];
    [self prepareTableView];
    // Do any additional setup after loading the view.
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    submitImageView.hidden = NO;
    backBtn.hidden = NO;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    submitImageView.hidden = YES;
    backBtn.hidden = YES;
}

-(void)setFloorArray:(NSMutableArray *)floorArray
{
    _floorArray = floorArray;
    floorDataArray = [[NSMutableArray alloc]init];
    originDataArray = [[NSMutableArray alloc]init];
    allSourceArray = [[NSMutableArray alloc]init];
    for (NSMutableArray * array in floorArray) {
//        NSMutableArray * modelArray = [[NSMutableArray alloc]init];
        for (FloorCardModel * model in array) {
            [originDataArray addObject:[model copy]];
            [allSourceArray addObject:[model copy]];
        }
//        [floorDataArray addObject:modelArray];
    }
    floorDataArray = [self LetterSortArray:allSourceArray];
    selectIndexArray = [self indexArray:allSourceArray];
    [floorTabelView reloadData];
}

-(void)prepareNavBtn
{
    submitImageView = [[UIImageView alloc]initWithFrame:CGRectMake(UI_SCREEN_WIDTH - 66, 2, 50, 40)];
    submitImageView.userInteractionEnabled = NO;
    UITapGestureRecognizer * submitTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(submit)];
    [submitImageView addGestureRecognizer:submitTap];
    [self.navigationController.navigationBar addSubview:submitImageView];
    
    submitLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, 50, 20)];
    submitLabel.text = NSLocalizedString(@"authenSubmit",@"完成");
    submitLabel.textColor = UIColorFromRGBAndA(0x7dc234, 0.5);
    submitLabel.font = [UIFont systemFontOfSize:15.0];
    submitLabel.textAlignment = NSTextAlignmentRight;
    [submitImageView addSubview:submitLabel];
    
    float x = 0;
    float y = 0;
    float width = 56;
    float height = 40;
    backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(x, y, width, height);
    [backBtn addTarget:self action:@selector(guestInfoBack) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:backBtn];
}

-(void)prepareTableView
{
    float x = 0;
    float y = 0;
    float width = UI_SCREEN_WIDTH;
    float height = UI_SCREEN_HEIGHT - 64;
    floorTabelView = [[UITableView alloc]initWithFrame:CGRectMake(x, y, width, height) style:UITableViewStyleGrouped];
    floorTabelView.delegate = self;
    floorTabelView.dataSource = self;
    floorTabelView.tableFooterView = [UIView new];
    floorTabelView.backgroundColor = UIColorFromRGB(0xebebeb);
    floorTabelView.sectionIndexBackgroundColor = [UIColor clearColor];
//    floorTabelView.sectionIndexColor = [UIColor redColor];
    [self.view addSubview:floorTabelView];
    
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return floorDataArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray * array = floorDataArray[section];
    return array.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44.0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 39.0;
    }
    else
    {
        return 34.0;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return selectIndexArray[section];
}

-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return selectIndexArray;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * identityId = @"cellId";
    FloorCardCell * cell = [tableView dequeueReusableCellWithIdentifier:identityId];
    if (!cell) {
        cell = [[FloorCardCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identityId];
    }
    NSArray * array = floorDataArray[indexPath.section];
    FloorCardModel * model = array[indexPath.row];
    cell.bulidingName = model.bulidingCardName;
    cell.floorName = model.floorCardName;
    cell.floorId = model.floorCardId;
    cell.isSelect = model.enable;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray * selectArray = floorDataArray[indexPath.section];
    FloorCardModel * model = selectArray[indexPath.row];
    model.enable = !model.enable;
    [selectArray replaceObjectAtIndex:indexPath.row withObject:model];
    [self submitStauts];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [floorTabelView reloadData];
}

#pragma mark -----------判断当前的选择项和原来是否有改变
-(BOOL)judgeSelect
{
    for (NSArray * sectionArray in floorDataArray) {
        for (FloorCardModel * model in sectionArray) {
            for (FloorCardModel * originModel in originDataArray) {
                if ([model.floorCardId isEqualToString:originModel.floorCardId]) {
                    if (originModel.enable != model.enable) {
                        return YES;
                    }
                }
            }
        }
    }
    return NO;
}

-(void)submitStauts
{
    if ([self judgeSelect]) {
        submitImageView.userInteractionEnabled = YES;
        submitLabel.textColor = UIColorFromRGBAndA(0x7dc234, 1.0);
    }
    else
    {
        submitImageView.userInteractionEnabled = NO;
        submitLabel.textColor = UIColorFromRGBAndA(0x7dc234, 0.5);
    }
}

#pragma mark -----------提交时计算当前的选中楼栋ID
-(NSMutableString *)selectFloorId
{
    NSMutableString * selectIdString = [[NSMutableString alloc]init];
    for (NSArray * selectIdArray in floorDataArray) {
        for (FloorCardModel * floorModel in selectIdArray) {
            if (floorModel.enable) {
                [selectIdString appendString:[NSString stringWithFormat:@"%@,",floorModel.floorCardId]];
            }
        }
    }
    if (selectIdString.length > 0) {
        selectIdString = [NSMutableString stringWithString:[selectIdString substringToIndex:(selectIdString.length - 1)]] ;
    }
    return selectIdString;
}

-(void)submit
{
    if ([self IsHaveNetwork]) {
        return;
    }
    NSString * floorIdString = [self selectFloorId];
    [self startWaiting:nil color:nil addToView:self.view];
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [postDict setValue:[QRSingleton sharedQRSingleton].communityId forKey:@"communityId"];
    [postDict setValue:_userId forKey:@"userId"];
    [postDict setValue:floorIdString forKey:@"floorId"];
    __weak FloorCardController * weakSelf = self;
    RequestNetWork * rnw = [[RequestNetWork alloc]init];
    [rnw initWithPath:POST(SAVEFLOORCARD) params:postDict block:^(id downLoadData, id error)
     {
         [self stopWaiting];
         if (downLoadData) {
             [PromptInfoView showMessage:NSLocalizedString(@"modifyPowerSuccess", nil)];
             if (weakSelf.IDBlock) {
                 weakSelf.IDBlock(floorIdString);
             }
             [self.navigationController popViewControllerAnimated:YES];
         }
         else
         {
             [PromptInfoView showMessage:[error objectForKey:@"info"]superView:self.view];
             
         }
     }];

}

#pragma mark -- 按照拼音排序
-(NSMutableArray*)getChinesArray:(NSArray*)arrToSort
{
    if (arrToSort.count == 0 || arrToSort == nil) {
        return nil;
    }
    //创建一个临时的变动数组
    int count = (int)arrToSort.count;
    for(int i =0; i < count; i++)
    {
        //创建一个临时的数据模型对象
        ChineseString *chineseString=[[ChineseString alloc]init];
        //给模型赋值
        FloorCardModel * model = [arrToSort objectAtIndex:i];
        NSString *pinYinResult = [NSString string];
        chineseString.string = model.bulidingCardName;
        if(chineseString.string==nil)
        {
            chineseString.string=@"";
        }
        if(![chineseString.string isEqualToString:@""])
        {
            //join(链接) the pinYin (letter字母) 链接到首字母
            char FirstHeader = pinyinFirstLetter([chineseString.string characterAtIndex:0]);
            if ((FirstHeader < 91 && FirstHeader > 64)||(FirstHeader < 123 && FirstHeader > 96)) {
                pinYinResult = [pinYinResult stringByAppendingString:[[NSString stringWithFormat:@"%c",FirstHeader]uppercaseString]];
            }else {
                pinYinResult = @"#";
            }
        }
        model.headerWord = pinYinResult;
    }
    
    NSMutableArray * array = [NSMutableArray arrayWithArray:[arrToSort sortedArrayUsingComparator:^NSComparisonResult(FloorCardModel * model1, FloorCardModel * model2) {
        return [model1.headerWord compare:model2.headerWord];
    }]];
    return array;
}

#pragma mark --------- 对排序好的进行归类
-(NSMutableArray*)LetterSortArray:(NSArray*)stringArr
{
    NSMutableArray *tempArray = [self getChinesArray:stringArr];
    NSMutableArray *LetterResult = [NSMutableArray array];
    NSMutableArray *item = [NSMutableArray array];
    NSString *tempString;
    //拼音分组
    for (FloorCardModel * model in tempArray) {
        
        NSString *pinyin = model.headerWord;
        //不同
        if(![tempString isEqualToString:pinyin])
        {
            //分组
            item = [NSMutableArray array];
            [item  addObject:model];
            [LetterResult addObject:item];
            //遍历
            tempString = pinyin;
        }else//相同
        {
            [item  addObject:model];
        }
    }
    return LetterResult;
}


#pragma mark -------------返回tableview右方的indexarray
-(NSMutableArray *)indexArray:(NSArray *)stringArr
{
    NSMutableArray *tempArray = [self getChinesArray:stringArr];
    NSMutableArray *A_Result = [NSMutableArray array];
    NSString *tempString ;
    
    for (FloorCardModel * model in tempArray)
    {
        NSString *pinyin = model.headerWord;
        //不同
        if(![tempString isEqualToString:pinyin])
        {
            [A_Result addObject:pinyin];
            tempString = pinyin;
        }
    }
    return A_Result;
}

#pragma mark ---------自定义返回键
-(void)guestInfoBack
{
    if ([self judgeSelect]) {
        UIAlertView * alterView = [[UIAlertView alloc]initWithTitle:nil message:NSLocalizedString(@"shouldSave", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"notSave", nil) otherButtonTitles:NSLocalizedString(@"save", nil), nil];
        [alterView show];
    }
    else
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        [self submit];
    }
    else
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
